package com.stylefeng.guns.modular.huamao.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.model.Shopping;
import com.stylefeng.guns.modular.huamao.model.SktShops;
import com.stylefeng.guns.modular.huamao.model.Users;
import com.stylefeng.guns.modular.huamao.mongodb.Chat;
import com.stylefeng.guns.modular.huamao.mongodb.OperationLog;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.ISktShopsService;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping(value = "/mongodb")
public class MongodbController {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private ISktShopsService  shopsService;

    @RequestMapping(value = "/getName")
    public Object getName(){
        String name = mongoTemplate.getDb().getName();
        return name;
    }
    @RequestMapping(value = "/getLog")
    public Object getLog(){
        Integer currentPage = 1;
        Integer pageSize = 10;
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"createtime"));
        query.skip((currentPage-1)*pageSize);
        query.limit(pageSize);
        List<OperationLog> logs = mongoTemplate.find(query,OperationLog.class);
        return logs;
    }

    /**
     * 获取聊天记录
     * @param currentPage
     * @param pageSize
     * @param userSendId
     * @param userReceiveId
     * @return
     */
    @RequestMapping(value = "/getChat")
    public Object getChat(Integer currentPage,Integer pageSize,String userSendId,String userReceiveId){
//        Integer currentPage = 1;
//        Integer pageSize = 10;
        List<String> list = new ArrayList<>();
//        list.add("user1");
//        list.add("5");
        list.add(userSendId);
        list.add(userReceiveId);
        Criteria criteria = Criteria.where("userSendId").in(list).and("userReceiveId").in(list);
        Query query = new Query(criteria);
        query.with(new Sort(Sort.Direction.DESC,"createtime"));
        query.skip((currentPage-1)*pageSize);
        query.limit(pageSize);
        List<Chat> chats = mongoTemplate.find(query,Chat.class);
        Collections.reverse(chats);
        Query query1 = new Query(criteria);
        Long count = mongoTemplate.count(query1,Chat.class);
        Double totalPages  = Double.valueOf(count)/Double.valueOf(pageSize);
        JSONObject jsonObject =  new JSONObject();
        jsonObject.put("chats",chats);
        jsonObject.put("totalPages",Math.ceil(totalPages));
        return jsonObject;
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getPicture")
    public JSONObject getPicture(Integer userId){
        Users users = new Users();
        users.setUserId(userId);
        EntityWrapper<Users> entityWrapper = new EntityWrapper<Users>(users);
        users = usersService.selectOne(entityWrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nickName",users.getLoginName());
        jsonObject.put("userPhoto",users.getUserPhoto());
        return jsonObject;
    }
    /**
     * 获取店铺用户信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getShopInfo")
    public JSONObject getShopInfo(Integer userId){
        SktShops sktShops = new SktShops();
        sktShops.setUserId(userId);
        EntityWrapper<SktShops> entityWrapper = new EntityWrapper<SktShops>(sktShops);
        sktShops = shopsService.selectOne(entityWrapper);
        if(sktShops == null){
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shopName",sktShops.getShopName());
        return jsonObject;
    }

    @RequestMapping(value = "/remove")
    public void remove(){
        Criteria criteria = Criteria.where("userReceiveId").is("user1");
        Query query = new Query(criteria);
        mongoTemplate.remove(query,Chat.class);
    }

    /**
     * 获取店铺用户id
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/getShopUserId")
    public Result getShopUserId(Integer shopId){
        SktShops sktShop = new SktShops();
        sktShop.setShopId(shopId);
        EntityWrapper<SktShops> entityWrapper = new EntityWrapper<SktShops>(sktShop);
        sktShop = shopsService.selectOne(entityWrapper);
       if (sktShop == null){
           return Result.EEROR("商家账户为空");
       }
       return Result.OK(sktShop.getUserId());
    }

    /**
     *普通用户获取最近联系人列表
     * @param userSendId
     * @return
     */
    @RequestMapping(value = "/chatLog")
    public Result chatLog(String userSendId){
//        Criteria criteria = Criteria.where("userSendId").is(userSendId).orOperator(Criteria.where("userReceiveId").is(userSendId));
        Criteria criteria = Criteria.where("userSendId").is(userSendId);
        Query query = new Query(criteria);
        List<Chat> chats = mongoTemplate.find(query,Chat.class);

        //chats.addAll(rchats);
        List<String> list = new ArrayList<>();
        for (Chat  chat:chats){
            list.add(chat.getUserReceiveId());
        }
//        if (list == null){
//            return Result.EEROR("列表为空");
//        }
        /**
         * 接受者用户Id列表去重
         */
        List<String> rlist = StringUtils.removeDuplicate(list);
        /***********************************获取接收端去重列表开始****************************************/
        Criteria rcriteria = Criteria.where("userReceiveId").is(userSendId);
        Query rquery = new Query(rcriteria);
        List<Chat> chats1 = mongoTemplate.find(rquery,Chat.class);

        List<String> list1 = new ArrayList<>();
        for (Chat  chat1:chats1){
            list.add(chat1.getUserSendId());
        }
        if (list == null && list1==null ){
            return Result.EEROR("列表为空");
        }
        List<String> rlist1 = StringUtils.removeDuplicate(list1);
        /***********************************获取接收端去重列表结束****************************************/
        rlist.addAll(rlist1);
        List<String> rlist2 = StringUtils.removeDuplicate(rlist);
        List<JSONObject> objectList =  new ArrayList<>();
        for (String s:rlist){
            if (!s.equals("null")){
                JSONObject jsonObject =  this.getPicture(Integer.parseInt(s));
                jsonObject.put("userReceiveId",s);
                objectList.add(jsonObject);
            }
        }
        return Result.OK(objectList);
    }

    /**
     * 店铺获取最近联系人列表
     * @param userReceiveId
     * @return
     */
    @RequestMapping(value = "/shopChatLog")
    public Result shopChatLog(String userReceiveId){
        Criteria criteria = Criteria.where("userReceiveId").is(userReceiveId);
        Query query = new Query(criteria);
        List<Chat> chats = mongoTemplate.find(query,Chat.class);
        List<String> list = new ArrayList<>();
        for (Chat  chat:chats){
            list.add(chat.getUserSendId());
        }
        if (list == null){
            return Result.EEROR("列表为空");
        }
        /**
         * 接受者用户Id列表去重
         */
        List<String> rlist = StringUtils.removeDuplicate(list);


        List<JSONObject> objectList =  new ArrayList<>();
        for (String s:rlist){
            JSONObject jsonObject =  this.getPicture(Integer.parseInt(s));
            jsonObject.put("userSendId",s);
            objectList.add(jsonObject);
        }
        return Result.OK(objectList);
    }
}
